package com.zhugy.comparecode.makefile;

import java.util.ArrayList;
import java.util.List;

import com.zhugy.comparecode.BaseCodeLine;
import com.zhugy.comparecode.CodeLine;
import com.zhugy.comparecode.CompareResult;
import com.zhugy.comparecode.util.CommonUtils;

public class MakefileCodeLine extends BaseCodeLine {
	
	private String content;
	
	private String[] parts;
	
	public MakefileCodeLine(int index, String content) {
		this.index = index;
		this.content = content;
		this.parts = parseParts(content);
	}

	private static String[] parseParts(String content) {
		List<String> partList = new ArrayList<>();
		if (CommonUtils.isEmpty(content)) {
			return new String[0];
		}
		StringBuilder temp = new StringBuilder();
		loop: for (int i = 0; i < content.length(); i++) {
			char c = content.charAt(i);
			switch (c) {
			case ' ':
				if (temp.length() > 0) {
					partList.add(temp.toString());
					temp.setLength(0);
					continue loop;
				}
				continue loop;
			case '+':
			case '-':
				if (temp.length() > 0) {
					partList.add(temp.toString());
					temp.setLength(0);
				}
				temp.append(c);
				if (nextCharEquals(content, i, '=')) {
					temp.append(content.charAt(i + 1));
					i++;
				}
				partList.add(temp.toString());
				temp.setLength(0);
				continue loop;
			case '>':
				if (temp.length() > 0) {
					partList.add(temp.toString());
					temp.setLength(0);
				}
				temp.append(c);
				if (nextCharEquals(content, i, '=') || nextCharEquals(content, i, '<')) {
					temp.append(content.charAt(i + 1));
					i++;
				}
				partList.add(temp.toString());
				temp.setLength(0);
				continue loop;
			case '<':
				if (temp.length() > 0) {
					partList.add(temp.toString());
					temp.setLength(0);
				}
				temp.append(c);
				if (nextCharEquals(content, i, '=') || nextCharEquals(content, i, '<')) {
					temp.append(content.charAt(i + 1));
					i++;
				}
				partList.add(temp.toString());
				temp.setLength(0);
				continue loop;
				default:
					temp.append(c);
					break;
			}
			
		}
		return partList.toArray(new String[0]);
	}
	
	private static boolean nextCharEquals(String content, int i, char c) {
		// 没有下一个字符了
		if (i >= content.length() - 1) {
			return false;
		}
		char nextChar = content.charAt(i + 1);
		if (nextChar == c) {
			return true;
		}
		return false;
	}

	@Override
	public CompareResult compareTo(CodeLine l) {
		if (!(l instanceof MakefileCodeLine)) {
			return CompareResult.fail("C代码行类型不一样");
		}
		MakefileCodeLine another = (MakefileCodeLine) l;
		String[] parts1 = this.parts;
		String[] parts2 = another.parts;
		for (int i = 0; i < parts1.length; i++) {
			if (i >= parts2.length) {
				return CompareResult.fail("左边的已经没有了，右边还存在:" + this.content + "     " + another.content);
			}
			if (!parts1[i].equals(parts2[i])) {
				return CompareResult.fail("第" + i + "个表达式不匹配"  + this.content + "     " + another.content);
			}
		}
		return CompareResult.success("");
	}

}
